package com.hefei.oss.serivce.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.PolicyConditions;
import com.hefei.oss.config.ConstanceProperties;
import com.hefei.oss.serivce.IOssService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author caizhengjun
 * @date 2021/3/5 下午6:35
 */
@Service
public class OssServiceImpl implements IOssService {

    @Autowired
    private ConstanceProperties constanceProperties;

    @Override
    public String upload(MultipartFile file) {

        String bucketName = constanceProperties.getBucketName();
        OSSClient ossClient = null;
        String fileHost = constanceProperties.getFileHost();
        String uploadUrl = null;
        try {
            ossClient =
                    new OSSClient(constanceProperties.getEndpoint(), constanceProperties.getAccessKeyId(), constanceProperties.getAccessKeySecret());

            if (!ossClient.doesBucketExist(bucketName)) {
                ossClient.createBucket(bucketName);
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }

            InputStream is = file.getInputStream();
            String filePath = new DateTime().toString("yyyy/MM/dd");
            String original = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString();
            String fileType = original.substring(original.lastIndexOf("."));
            String newName = fileName + fileType;
            String fileUrl = fileHost + "/" + filePath + "/" + newName;

            ossClient.putObject(bucketName, fileUrl, is);

            uploadUrl = "http://" + bucketName + "." + constanceProperties.getEndpoint() + "/" + fileUrl;
        } catch (IOException e) {

        } finally {

            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return uploadUrl;
    }
}
